<template>
  <AppDialogForm
    :title="props.userInfo.id ? '编辑用户信息' : '添加用户'"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.username"
          placeholder="请输入用户账号"
          :disabled="props.userInfo.id ? true : false"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!props.userInfo.id">
        <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" maxlength="11" />
      </el-form-item>
    </el-form>
  </AppDialogForm>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addUser, editUser } from "@/api/user.js";

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => {},
  },
});
const emit = defineEmits(["success"]);
const form = ref(null);
const loading = ref(false);
const formData = ref({
  username: "",
  password: "",
  email: "",
  mobile: "",
});

// 验证邮箱规则
const checkEmail = (rule, value, callback) => {
  let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的邮箱"));
  }
};
// 验证手机号规则
const checkMobile = (rule, value, callback) => {
  let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的手机号码"));
  }
};

const formRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: checkEmail, trigger: "blur" },
  ],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: checkMobile, trigger: "blur" },
  ],
};

const loadUser = () => {
  if (!props.userInfo.id) {
    return;
  }
  formData.value = { ...props.userInfo };
};

const handleDialogOpen = () => {
  loadUser();
};

const handleSubmit = async () => {
  const valid = await form.value.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  if (props.userInfo.id) {
    // 更新用户
    await editUser(formData.value).finally(() => {
      loading.value = false;
    });
    ElMessage.success("编辑用户信息成功");
  } else {
    // 添加用户
    await addUser(formData.value).finally(() => {
      loading.value = false;
    });
    ElMessage.success("添加用户成功");
  }
  emit("success");
};
const handleDialogClosed = () => {
  form.value.clearValidate(); // 清除验证结果
  form.value.resetFields(); // 清除表单数据
  formData.value = {
    username: "",
    password: "",
    email: [],
    mobile: "",
  };
};
</script>

<style lang="scss" scoped></style>
